package ca.cbc.giscommon.util;

import java.util.Calendar;
import java.util.Locale;

public enum CalendarUtil {
	instance;
	
	public long getFirstDayOfCurrentWeek() {
		Calendar now = Calendar.getInstance(Locale.CANADA);
		Calendar startTime = Calendar.getInstance(Locale.CANADA);
		startTime.clear();		
		startTime.set(now.get(Calendar.YEAR), now.get(Calendar.MONTH), now.get(Calendar.DAY_OF_MONTH));
		while(startTime.get(Calendar.DAY_OF_WEEK) > startTime.getFirstDayOfWeek()) {
			startTime.add(Calendar.DATE, -1);
		}
		
		return startTime.getTimeInMillis();
	}
	
	public long getFirstDayOfCurrentMonth() {
		Calendar now = Calendar.getInstance(Locale.CANADA);
		Calendar startTime = Calendar.getInstance(Locale.CANADA);
		startTime.clear();		
		startTime.set(now.get(Calendar.YEAR), now.get(Calendar.MONTH), 1);
		
		return startTime.getTimeInMillis();
	}
	
	public long getFirstDayOfNextMonth() {
		Calendar calendar = Calendar.getInstance(Locale.CANADA);
		calendar.clear();
		calendar.setTimeInMillis(getFirstDayOfCurrentMonth());
		calendar.add(Calendar.MONTH, 1);
		
		return calendar.getTimeInMillis();
	}
	
	public long getLastDayOfCurrentWeek() {
		Calendar calendar = Calendar.getInstance(Locale.CANADA);
		calendar.clear();
		calendar.setTimeInMillis(getFirstDayOfCurrentWeek());
		calendar.add(Calendar.DATE, 8); // to get the first day of next week.
		
		// remove one millisecond to get to end of last day of this week.
		return calendar.getTimeInMillis() - 1;  
	}
	
	public long getLastDayOfCurrentMonth() {
		return getFirstDayOfNextMonth() - 1;
	}
	
	public long getLastDayOfNextMonth() {
		Calendar calendar = Calendar.getInstance(Locale.CANADA);
		calendar.clear();
		calendar.setTimeInMillis(getFirstDayOfCurrentMonth());
		calendar.add(Calendar.MONTH, 2);
		
		return calendar.getTimeInMillis() - 1;
	}
	
	public long getStartTimeOfToday() {
		Calendar now = Calendar.getInstance(Locale.CANADA);
		Calendar startTime = Calendar.getInstance(Locale.CANADA);
		startTime.clear();
		
		startTime.set(now.get(Calendar.YEAR), now.get(Calendar.MONTH), now.get(Calendar.DAY_OF_MONTH));
		return startTime.getTimeInMillis();
	}
	
	public long getEndTimeOfToday() {
		Calendar calendar = Calendar.getInstance(Locale.CANADA);
		calendar.clear();
		calendar.setTimeInMillis(getStartTimeOfToday());
		calendar.add(Calendar.HOUR, 24);
		
		return calendar.getTimeInMillis() - 1;
	}
	
	public long getEndTimeOfDay(long time) {
		Calendar calendar = Calendar.getInstance(Locale.CANADA);
		calendar.clear();
		calendar.setTimeInMillis(time);
		
		Calendar endTime = Calendar.getInstance(Locale.CANADA);
		endTime.clear();
		
		endTime.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH));
		endTime.add(Calendar.DATE, 1);
		
		return endTime.getTimeInMillis() - 1;
	}
}
